package jp.co.kayo.gae.takidashibot.controller.takidasibot;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;

import jp.co.kayo.gae.takidashibot.controller.JsonController;
import jp.co.kayo.gae.takidashibot.meta.TakidasiMeta;
import jp.co.kayo.gae.takidashibot.model.Takidasi;
import jp.co.kayo.gae.takidashibot.utils.Utils;

import org.slim3.datastore.Datastore;
import org.slim3.util.RequestMap;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.repackaged.com.google.common.collect.Maps;

public class View2Controller extends JsonController {
    private SimpleDateFormat _sdf;

    public SimpleDateFormat getSDF(){
        if(_sdf == null){
            _sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
            TimeZone tz = TimeZone.getTimeZone("Asia/Tokyo");
            _sdf.setTimeZone(tz);
        }
        return _sdf;
    }
    
    @Override
    protected Map<String, Object> handle() throws Exception {
        RequestMap input = new RequestMap(request);
        
        String id = (String)input.get("id");
        String type = (String)input.get("t");
        String callback = (String)input.get("callback");
        
        if("jsonp".equals(type)){
            if(callback==null || callback.length()==0 || !callback.matches("/^[a-zA-Z]+$/")){
                setCallback("view");
            }
            else{
                setCallback(callback);
            }
        }
        
        //一件取得する
        if(id != null && id.length()>0){
            Key key = KeyFactory.createKey(Takidasi.class.getSimpleName(), id);
            Entity ent = Datastore.getOrNullWithoutTx(key);//.get(key);
            if(ent!=null){
                TakidasiMeta tm = TakidasiMeta.get();
                Takidasi t = tm.entityToModel(ent);
                
                StringBuilder urlstr = new StringBuilder();
                urlstr.append("http://maps.google.com/maps?q=")
                .append(t.getLat()).append(",")
                .append(t.getLng()).append("+(")
                .append(URLEncoder.encode(t.getName(), "UTF-8")).append(")");
                
                StringBuilder body = new StringBuilder();
                body.append(Utils.fixString(t.getDescription()));
                body.append(" ");
                
                Date date = new Date(t.getCreatedAt());
                body.append("(").append(getSDF().format(date)).append(" 登録)");
                
                Map<String, Object> map = Maps.newHashMap();
                map.put("body", body.toString());
                map.put("title", t.getName());
                map.put("map", urlstr.toString());
                return map;
            }
        }
        
        return Maps.newHashMap();
    }

}
